package com.backend.plat.sa.controller;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;

import com.backend.constants.Constant;
import com.backend.dto.UserDto;
import com.google.gson.reflect.TypeToken;
import com.oxygen.dto.ApiFinalResponse;
import com.oxygen.enums.BackendApiMethodEnum;
import com.oxygen.util.JsonUtil;

/**
 * 后台登录action
 * 
 * @author jason
 */
@Controller
public class BackendLoginAction extends BaseAction {
	
	

	/**
	 * 进入登录页面
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/login")
	public String login(HttpServletRequest req) {
		if (this.isLogon(req)) {
			return "redirect:/";
		}
		req.setAttribute("username", req.getParameter("username"));
		return "/login";
	}

	/**
	 * 登录
	 * 
	 * @param req
	 * @param rsp
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/doLogin")
	public String doLogin(HttpServletRequest req, HttpServletResponse rsp,
			RedirectAttributes redirectAttributes) {
		try {
			//校验登陆状态
			Map<String, Object> appendMap = new HashMap<String, Object>();
			String json = this.callApi(BackendApiMethodEnum.USER_LOGIN,
					appendMap, req);
			Type type = new TypeToken<Map<String, ApiFinalResponse<UserDto>>>() {
			}.getType();
			Map<String, ApiFinalResponse<UserDto>> retMap = JsonUtil
					.jsonToObject(json, type);
			if(retMap==null){
				return "redirect:login";
			}
			UserDto user = retMap.get(
					BackendApiMethodEnum.USER_LOGIN.getCode())
					.getResults();
			if(user!=null){
				WebUtils.setSessionAttribute(req,Constant.BACKEND_SESSION_USER_INFO, user);
				return "/index";
			}
			else{
				return "redirect:login";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:login";
	}
	
	/**
	 * 登出
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest req) {
		req.getSession().invalidate();
		return "redirect:/login";
	}
}
